package com.dlc.shop.multishop.controller;

import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dlc.shop.bean.enums.ProdStatusEnums;
import com.dlc.shop.bean.model.Supplier;
import com.dlc.shop.bean.model.SupplierCategory;
import com.dlc.shop.bean.vo.SupplierVO;
import com.dlc.shop.common.config.Constant;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.common.util.PageParam;
import com.dlc.shop.common.util.PrincipalUtil;
import com.dlc.shop.security.multishop.util.SecurityUtils;
import com.dlc.shop.service.ProductService;
import com.dlc.shop.service.SupplierCategoryService;
import com.dlc.shop.service.SupplierService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author OPGame
 * @date 2020-08-25 15:50:06
 */
@RestController
@RequestMapping("/supplier/supplier")
@Tag(name = "供应商接口")
@AllArgsConstructor
public class SupplierController {

    private final SupplierService supplierService;
    private final ProductService productService;
    private final SupplierCategoryService supplierCategoryService;

    @GetMapping("/page")
    @Schema(description = "分页获取供应商信息" )
    @PreAuthorize("@pms.hasPermission('supplier:supplier:page')")
    public ServerResponseEntity<IPage<Supplier>> getSupplierPage(PageParam<Supplier> page, Supplier supplier) {
        supplier.setShopId(SecurityUtils.getShopUser().getShopId());
        IPage<Supplier> suppliers = supplierService.pageShop(page, supplier);
        for (Supplier suppliersRecord : suppliers.getRecords()) {
            String tel = suppliersRecord.getTel();
            if (StrUtil.isNotBlank(tel)) {
                String after = !tel.contains("-") ? tel : tel.split("-")[1];
                String afterHide = PhoneUtil.hideBetween(after).toString();
                String before = !tel.contains("-") ? "" : tel.split("-")[0] + "-";
                suppliersRecord.setTel(before + afterHide);
            }
            if (StrUtil.isNotBlank(suppliersRecord.getContactTel()) && PrincipalUtil.isMobile(suppliersRecord.getContactTel())) {
                suppliersRecord.setContactTel(PhoneUtil.hideBetween(suppliersRecord.getContactTel()).toString());
            }
        }
        return ServerResponseEntity.success(suppliers);
    }

    @GetMapping("/prodSupplierPage")
    @Schema(description = "分页获取供应商商品信息" )
    @PreAuthorize("@pms.hasPermission('supplier:supplier:page')")
    public ServerResponseEntity<IPage<SupplierVO>> getProdSupplierPage(PageParam<Supplier> page, Supplier supplier) {
        supplier.setShopId(SecurityUtils.getShopUser().getShopId());
        IPage<SupplierVO> prodSupplier = supplierService.pageProdSupplier(page, supplier);
        SupplierVO supplierVO = null;
        // 获取自采供应商的数据
        for (SupplierVO record:prodSupplier.getRecords()) {
            if (Objects.equals(record.getIsDefault(),1)){
                supplierVO = record;
            }
        }
        // 如果有自采供应商，插入商品数量
        if (Objects.nonNull(supplierVO)) {
            int count = productService.getProductNum(supplier.getShopId(),ProdStatusEnums.DELETE.getValue());
            supplierVO.setSupplierProdCount(count);
        }
        return ServerResponseEntity.success(prodSupplier);
    }

    @GetMapping("/list")
    @Operation(summary = "获取供应商品列表" , description = "获取供应商品列表")
    @PreAuthorize("@pms.hasPermission('supplier:supplier:list')")
    public ServerResponseEntity<List<Supplier>> listSupplier() {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        List<Supplier> supplierList = supplierService.list(Wrappers.lambdaQuery(Supplier.class)
                .eq(Supplier::getShopId, shopId)
        );
        for (Supplier suppliersRecord : supplierList) {
            String tel = suppliersRecord.getTel();
            if (StrUtil.isNotBlank(tel)) {
                String after = !tel.contains("-") ? tel : tel.split("-")[1];
                String afterHide = PhoneUtil.hideBetween(after).toString();
                String before = !tel.contains("-") ? "" : tel.split("-")[0] + "-";
                suppliersRecord.setTel(before + afterHide);
            }
            if (StrUtil.isNotBlank(suppliersRecord.getContactTel()) && PrincipalUtil.isMobile(suppliersRecord.getContactTel())) {
                suppliersRecord.setContactTel(PhoneUtil.hideBetween(suppliersRecord.getContactTel()).toString());
            }
        }
        return ServerResponseEntity.success(supplierList);
    }

    @GetMapping("/info/{supplierId}")
    @Operation(summary = "根据id查询商品信息" , description = "根据id查询商品信息")
    @PreAuthorize("@pms.hasPermission('supplier:supplier:info')")
    public ServerResponseEntity<Supplier> getById(@PathVariable("supplierId") Long supplierId) {
        Supplier supplier = supplierService.getById(supplierId);
        if (!Objects.equals(SecurityUtils.getShopUser().getShopId(), supplier.getShopId())) {
            throw new YamiShopBindException("yami.no.auth");
        }
        String tel = supplier.getTel();
        if (StrUtil.isNotBlank(tel)) {
            String after = !tel.contains("-") ? tel : tel.split("-")[1];
            String afterHide = PhoneUtil.hideBetween(after).toString();
            String before = !tel.contains("-") ? "" : tel.split("-")[0] + "-";
            supplier.setTel(before + afterHide);
        }
        if (StrUtil.isNotBlank(supplier.getContactTel()) && PrincipalUtil.isMobile(supplier.getContactTel())) {
            supplier.setContactTel(PhoneUtil.hideBetween(supplier.getContactTel()).toString());
        }
        return ServerResponseEntity.success(supplier);
    }

    @PostMapping
    @PreAuthorize("@pms.hasPermission('supplier:supplier:save')")
    @Operation(summary = "新增供应商" , description = "新增供应商")
    public ServerResponseEntity<Boolean> save(@RequestBody @Valid Supplier supplier) {
        this.checkInfo(supplier);
        supplier.setShopId(SecurityUtils.getShopUser().getShopId());
        supplier.setCreateTime(new Date());
        supplier.setIsDefault(0);
        return ServerResponseEntity.success(supplierService.save(supplier));
    }

    @PutMapping
    @PreAuthorize("@pms.hasPermission('supplier:supplier:update')")
    @Operation(summary = "修改供应商" , description = "修改供应商")
    public ServerResponseEntity<Boolean> updateById(@RequestBody @Valid Supplier supplier) {
        this.checkInfo(supplier);
        Supplier dbSupplier = supplierService.getById(supplier.getSupplierId());
        if (Objects.isNull(dbSupplier)) {
            throw new YamiShopBindException("yami.prod.common.invalid");
        }
        if (StrUtil.isNotBlank(supplier.getTel()) && PrincipalUtil.isAsteriskTel(supplier.getTel())) {
            if (!PrincipalUtil.isDbPhone(supplier.getTel(), dbSupplier.getTel(), true)) {
                throw new YamiShopBindException("yami.user.err.phone");
            }
            if (supplier.getTel().contains(Constant.ASTERISK)) {
                supplier.setTel(dbSupplier.getTel());
            }
        }
        if (StrUtil.isNotBlank(supplier.getContactTel()) && PrincipalUtil.isAsteriskMobile(supplier.getContactTel())) {
            if (!PrincipalUtil.isDbPhone(supplier.getContactTel(), dbSupplier.getContactTel(), true)) {
                throw new YamiShopBindException("yami.user.err.phone");
            }
            if (supplier.getContactTel().contains(Constant.ASTERISK)) {
                supplier.setContactTel(dbSupplier.getContactTel());
            }
        }
        supplier.setUpdateTime(new Date());
        if (!Objects.equals(supplier.getIsDefault(),1)){
            supplier.setIsDefault(0);
        }
        return ServerResponseEntity.success(supplierService.updateSupplier(supplier));
    }

    @GetMapping("/exportSupplier")
    @Schema(description = "导出供应商" )
    @PreAuthorize("@pms.hasPermission('supplier:supplier:export')")
    public void exportSupplier(Supplier supplier, HttpServletResponse response) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        supplier.setShopId(shopId);
        supplierService.exportSupplier(supplier, response);
    }

    @GetMapping("/downLoadModel")
    @Schema(description = "下载导入供应商模板" )
    @PreAuthorize("@pms.hasPermission('supplier:supplier:downLoad')")
    public void downLoadModel(HttpServletResponse response) {
        supplierService.downLoadModel(SecurityUtils.getShopUser().getShopId(), response);
    }

    @Operation(summary = "导入供应商" , description = "导入供应商")
    @PostMapping("/importExcel")
    @ResponseBody
    @PreAuthorize("@pms.hasPermission('supplier:supplier:import')")
    public ServerResponseEntity<Object> importExcel(@RequestParam("excelFile") MultipartFile excelFile) throws Exception {
        if (Objects.isNull(excelFile)) {
            throw new YamiShopBindException("yami.network.busy");
        }
        Object o = supplierService.parseFile(excelFile, SecurityUtils.getShopUser().getShopId());
        return ServerResponseEntity.success(o);
    }

    private void checkInfo(Supplier supplier) {
        Integer nameNumber = supplierService.getCountByName(supplier.getSupplierName(), supplier.getSupplierId(),SecurityUtils.getShopUser().getShopId());
        if (nameNumber >= 1) {
            throw new YamiShopBindException("yami.supplier.supplierName.exist");
        }
        if (Objects.nonNull(supplier.getSupplierCategoryId())) {
            SupplierCategory supplierCategory = supplierCategoryService.getOne(new LambdaQueryWrapper<SupplierCategory>()
                    .eq(SupplierCategory::getSupplierCategoryId, supplier.getSupplierCategoryId()));
            if (Objects.equals(supplierCategory.getStatus(), 0)) {
                //供应商分类不存在或已被禁用
                throw new YamiShopBindException("yami.supplier.category.not.exit");
            }
        }
    }
}
